package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    private static final Integer MAX_PAGE_SIZE = 50;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Override
    public ResponseResult load(ArticleHomeDto dto, Short tagType) {
//        if (ArticleConstants.DEFAULT_TAG.equals(dto.getTag())){
//            apArticleMapper.loadArticleList(dto,tagType);
//        }

        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        size = Math.min(dto.getSize(), MAX_PAGE_SIZE);
        dto.setSize(size);
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());

        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, tagType);


        return ResponseResult.okResult(articleList);
    }

    /**
     * 保存app端文章
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) throws Exception {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        if (articleDto.getId() == null) {

            save(apArticle);

            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setContent(articleDto.getContent());
            articleContent.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(articleContent);

            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(Boolean.TRUE);
            apArticleConfig.setIsDelete(Boolean.FALSE);
            apArticleConfig.setIsDown(Boolean.FALSE);
            apArticleConfig.setIsForward(Boolean.TRUE);

            apArticleConfigMapper.insert(apArticleConfig);


        } else {


            //修改  文章
            updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleDto.getId()));
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(apArticleContent);

            ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, articleDto.getId()));
            apArticleConfig.setIsDown(articleDto.getIsDown());
            apArticleConfigMapper.updateById(apArticleConfig);
        }


        createDetails(apArticle.getId());


        return ResponseResult.okResult(apArticle.getId());
    }


    @Autowired
    private Configuration configuration;

    @Autowired
    private ApArticleContentMapper articleContentMapper;
    @Autowired
    private ApArticleMapper articleMapper;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 创建文章静态页面
     *
     * @param id
     * @return
     */
    @Override
    @Async
    public ResponseResult createDetails(Long id) throws Exception {
        // 删除minio中原有的url.html
        ApArticle apArticle = articleMapper.selectById(id);
        String staticUrl = apArticle.getStaticUrl();
        if (staticUrl!=null) {
            fileStorageService.delete(staticUrl);
        }

        //1.获取文章内容
        ApArticleContent apArticleContent = articleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, id));

        if (apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())) {
            //2.文章内容通过freemarker生成html文件
            StringWriter out = new StringWriter();
            Template template = configuration.getTemplate("article.ftl");

            Map<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(apArticleContent.getContent()));

            template.process(params, out);
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());

            //3.把html文件上传到minio中
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

            //4.修改ap_article表，保存static_url字段
            ApArticle article = new ApArticle();
            article.setId(apArticleContent.getArticleId());
            article.setStaticUrl(path);
            articleMapper.updateById(article);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_SYNC_FAIL);

    }


}